package com.cloudlead.plugin.security.service.impl;

import com.cloudlead.common.lang.security.Subject;
import com.cloudlead.common.lang.service.AbstractBaseService;
import com.cloudlead.common.worker.security.TokenInfoService;
import com.cloudlead.plugin.security.BusinessModules;
import com.cloudlead.plugin.security.service.TokenService;
import com.cloudlead.utils.cache.CacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class TokenServiceImpl extends AbstractBaseService implements TokenService {
    @Autowired
    private CacheService cacheService;

    @Autowired
    private TokenInfoService tokenInfoService;

    public TokenServiceImpl() {
        super(BusinessModules.ScUser);
    }

    @Override
    public void addSubject(String accessToken, Subject subject) {
        cacheService.set(TokenInfoService.ACCESS_TOKEN_CACHE + accessToken, subject, ACCESS_TOKEN_EXP_SECONDS);
    }

    @Override
    public void addAccessToken(String username, String accessToken) {
        cacheService.set(TokenInfoService.USERNAME_ACCESS_TOKEN_CACHE + username, accessToken, ACCESS_TOKEN_EXP_SECONDS);
    }

    @Override
    public void removeToken(String accessToken) {
        Subject subject = tokenInfoService.getSubjectByAccessToken(accessToken);
        cacheService.delete(TokenInfoService.ACCESS_TOKEN_CACHE + accessToken);
        if (null != subject) {
            cacheService.delete(TokenInfoService.USERNAME_ACCESS_TOKEN_CACHE + subject.getPrincipal().getUsername());
        }
    }

}
